const { think } = require('thinkjs');
const Base = require('./base.js');
const moment = require('moment/moment.js');
const { default: BigNumber } = require('bignumber.js');

module.exports = class extends Base {
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const model = this.model('account_list');
    const query = this.get();

    delete query.page;
    delete query.size;

    if (query.phone) {
      query.phone = ['like', `%${query.phone}%`];
    }

    if (query.name) {
      query.name = ['like', `%${query.name}%`];
    }

    const data = await model
      .where(query)
      .order(['id ASC'])
      .page(page, size)
      .countSelect();

    return this.success(data);
  }

  async listAllAction() {
    const data = await this.model('account_list').select();
    return this.success(data);
  }

  async detailAction() {
    if (this.get('token')) {
      const aiModel = await this.service('process', 'admin').detail(
        this.get('token')
      );
      return this.success(aiModel);
    }
    if (this.get('id')) {
      const data = await this.model('paper_list')
        .where({ id: this.get('id') })
        .find();
      return this.success(data);
    }
  }

  async putAction() {
    const values = this.post();
    const id = this.post('id');
    const model = this.model('account_list');

    if (id > 0) {
      await model.where({ id: id }).update(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑账户',
        content: id,
      });
    } else {
      delete values.id;
      const addId = await model.add(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新增账户',
        content: addId,
      });
    }
    return this.success(values);
  }

  async delAction() {
    const id = this.get('id');
    await this.model('paper_list')
      .where({ id: id })
      .update({ del: 1 });

    return this.success();
  }

  async accrualAction() {
    const page = this.post('page') || 1;
    const size = this.post('size') || 20;
    const dateRange = this.post('dateRange');
    const type = this.post('search_type');
    const projectId = this.post('project_id');
    let showInfo = true;

    const query = { 'a.status': 0, 'a.pass': 0, 'a.type': ['!=', 'yajin'] };
    // 查询所有未结算的账单
    if (think.isEmpty(dateRange)) {
      query['a.delay'] = 1;
    } else {
      query['a.remind_date'] = [
        'between',
        moment(dateRange[0])
          .startOf('month')
          .format('YYYY-MM-DD'),
        moment(dateRange[1])
          .endOf('month')
          .format('YYYY-MM-DD'),
      ];
      showInfo = false;
    }

    if (!think.isEmpty(projectId)) {
      query['c.project_id'] = projectId;
    }

    if (!think.isEmpty(type)) {
      query['a.type'] = ['IN', type];
    }
    query['a.tuizu'] = 0;

    let data;

    if (this.post('type') === '1') {
      data = await this.model('income_list')
        .where(query)
        .alias('a')
        .join({
          contract_list: {
            join: 'left',
            as: 'c',
            on: ['contract_id', 'id'],
          },
        })
        .field('a.*, c.title')
        .order(['a.remind_date DESC'])
        .page(page, size)
        .countSelect();
    } else if (this.post('type') === '2') {
      data = await this.model('output_list')
        .where(query)
        .alias('a')
        .join({
          contract_list: {
            join: 'left',
            as: 'c',
            on: ['contract_id', 'id'],
          },
        })
        .field('a.*, c.title')
        .order(['a.remind_date DESC'])
        .page(page, size)
        .countSelect();
    }
    data.total1 =
      (await this.model('income_list')
        .where(query)
        .alias('a')
        .join({
          contract_list: {
            join: 'left',
            as: 'c',
            on: ['contract_id', 'id'],
          },
        })
        .sum('money')) || 0;
    data.total2 =
      (await this.model('output_list')
        .where(query)
        .alias('a')
        .join({
          contract_list: {
            join: 'left',
            as: 'c',
            on: ['contract_id', 'id'],
          },
        })
        .sum('money')) || 0;

    data.rest = BigNumber(data.total1)
      .minus(BigNumber(data.total2))
      .toFixed(0);
    // if (query.phone) {
    //   query.phone = ['like', `%${query.phone}%`];
    // }

    // if (query.name) {
    //   query.name = ['like', `%${query.name}%`];
    // }
    const oType = [
      {
        label: '租金',
        value: 'fangzu',
      },
      {
        label: '物业',
        value: 'wuye',
      },
      {
        label: '押金',
        value: 'yajin',
      },
    ];
    const iType = [
      {
        label: '租金',
        value: 'fangzu',
      },
      {
        label: '物业',
        value: 'wuye',
      },
      {
        label: '电费押金',
        value: 'yajinShuidian',
      },
      {
        label: '装修押金',
        value: 'yajinZhuangxiu',
      },
      {
        label: '租赁押金',
        value: 'yajin',
      },
      {
        label: '其它费用',
        value: 'qita',
      },
    ];

    // const data = await model
    for (const item of data.data) {
      if (item.circle_start && item.circle_end) {
        item.circle = item.circle_start + '~' + item.circle_end;
      }
      if (this.post('type') === '1') {
        iType.forEach((res) => {
          if (res.value === item.type) {
            item.type = res.label;
            return;
          }
        });
      } else if (this.post('type') === '2') {
        oType.forEach((res) => {
          if (res.value === item.type) {
            item.type = res.label;
          }
          return;
        });
      }
    }
    data.showInfo = showInfo;

    return this.success(data);
  }
};
